﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class main_Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            if (IsUserExists(username))
            {
                lblMessage.Text = "用户名已存在，请选择其他用户名";
                return;
            }

            string sql = "INSERT INTO T_user (Username, Password) VALUES (@Username, @Password)";

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@Username", username);
                    cmd.Parameters.AddWithValue("@Password", password);

                    conn.Open();
                    int result = cmd.ExecuteNonQuery();
                    conn.Close();

                    if (result > 0)
                    {
                        lblMessage.Text = "注册成功！";
                        Response.Redirect("Login.aspx");
                    }
                    else
                    {
                        lblMessage.Text = "注册失败，请重试";
                    }
                }
            }
        }
    }

    private bool IsUserExists(string username)
    {
        string sql = "SELECT COUNT(*) FROM T_user WHERE Username = @Username";

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@Username", username);
                conn.Open();
                int count = (int)cmd.ExecuteScalar();
                conn.Close();
                return count > 0;
            }
        }
    }
}